<?php

namespace app\exception;

use support\Log;
use Throwable;
use Webman\Exception\ExceptionHandlerInterface;
use Webman\Http\Request;
use Webman\Http\Response;

class Handler implements ExceptionHandlerInterface
{


    /**
     * 记录日志
     * @param Throwable $exception
     * @return true
     */
    public function report(Throwable $exception): true
    {
        return true;
    }


    /**
     * 渲染返回
     * @param Request $request
     * @param Throwable $exception
     * @return Response
     */
    public function render(Request $request, Throwable $exception): Response
    {

        $defaultErrorText = "服务器出错，请稍后再试";

        // 404 页面不存在
        // 500 通用错误码
        // 501 角色售卖操作认证失效
        // 999 登录失效
        if (in_array($exception->getCode(), [404, 500, 501, 999])) {  // 自定义错误信息
            $code = $exception->getCode();
            $message = empty($exception->getMessage()) ? $defaultErrorText : $exception->getMessage();
        } else {  // 框架错误信息
            $code = 500;
            $message = $defaultErrorText;
        }

        Log::channel('error')->error(date('Y-m-d H:i:s'), [
            'code' => $exception->getCode(),
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
        ]);

        return jsonRe(array(), $code, $message);

    }

}